package com.lvbaoins.creditapp.core.Interceptor;

import com.lvbaoins.creditapp.core.exception.ServiceException;
import com.lvbaoins.creditapp.core.exception.enums.ErrorExceptionEnum;
import com.lvbaoins.creditapp.util.UserTokenManager;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.logging.Logger;

public class AuthenticationInterceptor extends HandlerInterceptorAdapter {

    public static final String LOGIN_TOKEN_KEY = "X-lvbaoins-Token";

    private Logger logger = Logger.getLogger("AuthenticationInterceptor");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        String token = request.getHeader(LOGIN_TOKEN_KEY);
        logger.info("[权限]-用户url:" + request.getRequestURL().toString() + ",token：" + token);
        if (token == null || token.isEmpty()) {
            logger.info("[权限]-错误，token为空");
            throw new ServiceException(ErrorExceptionEnum.NOT_LOGINING);
        }
        Integer userId = UserTokenManager.getUserId(token);
        if (userId == null) {
            logger.info("[权限]-错误，根据token获取不到用户信息，token：" + token);
            throw new ServiceException(ErrorExceptionEnum.NOT_LOGINING);
        }
        logger.info("[权限]-通过，用户id:" + userId);
        return true;
    }
}
